<template>
    <div class="recipes-add-or-update">
        <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="100px">
            <el-form-item label="菜谱名" prop="mainText">
                <el-input v-model="formData.mainText"></el-input>
            </el-form-item>
            <el-form-item label="主图">
                <el-upload :action="url" :show-file-list="false" :on-success="handleUploadSuccess"
                    :before-upload="beforeUpload" multiple>
                    <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
                </el-upload>

                <img v-if="formData.mainSrc" :src="formData.mainSrc" alt="主图" style="max-width: 200px; max-height: 200px;">
                <el-button @click="removeMain()" size="small" type="danger">删除主图</el-button>
            </el-form-item>
            <el-form-item label="制作步骤">
                <el-button @click="addStep" size="small" type="primary">新增步骤</el-button>
                <div v-for="(step, index) in formData.recipesDetailList" :key="index" class="step-item">
                    <el-input v-model="step.text" placeholder="请输入制作步骤" style="margin-bottom: 10px;"></el-input>
                    <el-upload :action="url" :show-file-list="false" :on-success="handleStepUploadSuccess(index)"
                        :before-upload="beforeStepUpload(index)">
                        <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
                    </el-upload>
                    <img v-if="step.src" :src="step.src" alt="步骤图" style="max-width: 200px; max-height: 200px;">
                    <el-button @click="removeStep(index)" size="small" type="danger">删除步骤</el-button>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button @click="back()">返回</el-button>
                <el-button v-if="recipesId === 0" type="primary" @click="submitForm('新增')">新增</el-button>
                <el-button v-else type="primary" @click="submitForm('修改')">修改</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
  
<script>
export default {
    data() {
        return {
            spuId: 0,
            recipesId: 0,
            url: '',
            formData: {},
            formRules: {
                mainText: [
                    { required: true, message: '请输入菜谱名', trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        removeMain() {
            if(this.recipesId === 0){
                this.$http({
                url: this.$http.adornUrl(`/minio/delete`),
                method: 'get',
                params: this.$http.adornParams({
                    'name': this.formData.mainSrc
                })
            }).then(({ data }) => {
                console.log(data)
            })
            }
            this.formData.mainSrc=''
        },
        // 上传主图成功回调
        handleUploadSuccess(response, file, fileList) {

            this.formData.mainSrc = response;

        },
        // 上传步骤图片成功回调
        handleStepUploadSuccess(index) {
            return (response, file, fileList) => {
                this.formData.recipesDetailList[index].src = response;
            };
        },
        // 新增步骤
        addStep() {
            this.formData.recipesDetailList.push({ src: '', text: '' });
        },
        // 删除步骤
        removeStep(index) {
            const deletedSrc = this.formData.recipesDetailList[index].src;
            //判断src是否为空
            if (deletedSrc) {
                //删除步骤图片
                if(this.recipesId === 0){
                this.$http({
                    url: this.$http.adornUrl(`/minio/delete`),
                    method: 'get',
                    params: this.$http.adornParams({
                        'name': deletedSrc
                    })
                }).then(({ data }) => {
                    console.log(data)
                })
            }
        }
            this.formData.recipesDetailList.splice(index, 1);
        },
        // 表单提交
        submitForm(action) {
            if (action === '新增') {
                const RecipesVo = {
                    spuId: this.spuId,
                    recipesId: this.recipesId,
                    recipesDetailList: this.formData
                }
                this.$http({
                    url: this.$http.adornUrl(`/web/recipes/save`),
                    method: 'post',
                    data: RecipesVo
                }).then(({ data }) => {
                    console.log(data)
                })
            }
            if (action === '修改') {
                const RecipesVo = {
                    spuId: this.spuId,
                    recipesId: this.recipesId,
                    recipesDetailList: this.formData
                }
                this.$http({
                    url: this.$http.adornUrl(`/web/recipes/update`),
                    method: 'post',
                    data: RecipesVo
                }).then(({ data }) => {
                    console.log(data)
                })
            }
            this.back()
        },
        // 返回按钮点击事件
        back() {
            const id = this.spuId
            this.$router.push({ name: 'recipes', params: { id } });
            console.log(this.recipesId)
            if (this.recipesId === 0) {
                console.log(this.formData.mainSrc)
                if (this.formData.mainSrc !== '') {
                    this.removeMain()
                }
                for (let i = 0; i < this.formData.recipesDetailList.length; i++) {
                    if (this.formData.recipesDetailList[i].src !== '') {
                        this.removeStep(i)
                    }
                }
            }
        },
        // 上传前的钩子函数
        beforeUpload(file) {
            // 在这里可以对上传的文件进行限制，比如文件类型、大小等
            return true;
        },
        // 步骤图片上传前的钩子函数
        beforeStepUpload(index) {
            return (file) => {
                // 在这里可以对步骤图片上传的文件进行限制，比如文件类型、大小等
                return true;
            };
        },
        // 初始化表单数据
        initFormData() {
            if (this.recipesId === 0) {
                // 新增模式，清空表单数据
                this.formData = {
                    mainSrc: '',
                    mainText: '',
                    recipesDetailList: []
                };
            } else {
                this.$http({
                    url: this.$http.adornUrl(`/web/recipes/get/${this.recipesId}`),
                    method: 'get',
                }).then(({ data }) => {
                    this.formData = data.recipes.recipesDetailList
                })
            }
        }
    },
    activated() {
        console.log("1111")
        // 根据路由参数设置 spuId
        this.spuId = this.$route.params.spuId;
        this.recipesId = this.$route.params.id;
        // 根据 spuId 初始化表单数据
        this.initFormData();
        this.url = this.$http.adornUrl(`/minio/upload?token=${this.$cookie.get('token')}`)
    },
    created() {

    },
    mounted() {

    }

};
</script>
  
<style scoped>
.step-item {
    margin-bottom: 20px;
}
</style>
  